<?php

/**
 * Template Handler
 *
 */
class Template
{
	private $var = array();
	private $filename = '';
	/**
	 * Directory containing templates
	 * @var string
	 */
	public static $folder = 'themes/';
	/**
	 * Current theme name
	 * @var string
	 */
	public static $theme = 'basic';


	public function __construct($name, $mod = null)
	{
		is_null($mod) && $mod = mod::$current;
		$mod = mod::get_name($mod);
		if ($mod !== 'system' ) {
			if (file_exists($this->filename = self::$folder . self::$theme . '/' . $mod . '/' . $name . '.phtml')) {
				return;
			}
			if (file_exists($this->filename = 'mod/' . $mod . '/tmpl/' . $name . '.phtml')) {
				return;
			}
		}
		if (!file_exists($this->filename = self::$folder . self::$theme . '/' . $name . '.phtml')) {
			trigger_error('Template "' . $name . '" not found', E_USER_NOTICE);
			$this->filename = '';
		}
	}

	/**
	 * Assign a value to be substituted in the template
	 * @param $var
	 * @param $val
	 * @return Template
	 */
	public function assign($var, $val)
	{
		$this->var[$var] = $val;
		return $this;
	}

	/**
	 * assign values from associative array
	 * @param $array
	 * @return Template
	 */
	public function assign_r(array $array)
	{
		foreach ($array as $var => $val) {
			$this->assign($var, $val);
		}
		return $this;
	}

	/**
	 * Add a value to be substituted in the template
	 * @param $var
	 * @param $val
	 * @return unknown_type
	 */
	public function add($var, $val)
	{
		if (!array_key_exists($var, $this->var) || !is_array($this->var[$var])) {
			$this->var[$var] = array();
		}
		$this->var[$var][] = $val;
		return $this;
	}

	public function process()
	{
		if (!file_exists($this->filename)) {
			return null;
		}
		if (defined('DEBUG')) {
			$err = error_reporting();
			error_reporting($err & ~E_NOTICE);
		}
		extract($this->var);
		ob_start();
		include $this->filename;
		defined('DEBUG') && error_reporting($err);
		return ob_get_clean();
	}


	public function flush()
	{
		if (!file_exists($this->filename)) {
			return false;
		}
		if (defined('DEBUG')) {
			$err = error_reporting();
			error_reporting($err & ~E_NOTICE);
		}
		extract($this->var);
		include $this->filename;
		defined('DEBUG') && error_reporting($err);
		return true;
	}

	public function __toString()
	{
		return $this->process();
	}

	protected function js($file)
	{
		$path = self::$folder . self::$theme . '/js/' . $file;
		if (!file_exists($path)) {
			$path = self::$folder . 'basic/js/' . $file;
		}
		return '<script type="text/javascript" src="/' . $path . '"></script>';
	}

	protected function css($file)
	{
		$path = self::$folder . self::$theme . '/css/' . $file;
		if (!file_exists($path)) {
			$path = self::$folder . 'basic/css/' . $file;
		}
		return '<link rel="stylesheet" href="/' . $path . '" />';
	}

}


?>